import AuthComponent from '@/components/Authorized/AuthComponent';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, message, DatePicker, Select } from 'antd';
import React, { useState, useCallback, useRef, useEffect } from 'react';
import ProTable from '@ant-design/pro-table';
import { useRequest } from '@umijs/hooks';
import moment from 'moment';
import styles from './index.less';
import { _dOrI, _accidentType } from './_data'
import { irregularluggagedetailTable, downloadluggagedetailExcel, queryCityInfo } from '../service';

let hiddenData = null;
const { Option } = Select;

const Compensationlist = (props) => {

  const actionRef = useRef();
  const ref = useRef();

  // 表格高度
  const [height, controlH] = useState(300);
  // 表格是否折叠
  const [isCollapse, controlC] = useState(true);
  // 存储搜索条件
  const [searchParams, handleSearchParams] = useState()
  // 表格是否有数据
  const [exportFlag, handleExportFlag] = useState(false)
  // 是否为第一次加载
  const [firstLoadDate, setFirstLoadDate] = useState(true);

  // 航站接口
  const { data: selectData } = useRequest(queryCityInfo);

  // 获取列表详情方法
  const beforeSearchSubmit = useCallback(params => {

    params['startDate'] = params.startDate ? params.startDate.format('YYYY-MM-DD') : '';
    params['endDate'] = params.endDate ? params.endDate.format('YYYY-MM-DD') : '';

    if (!isCollapse) {
      handleSearchParams(params)
      return { ...params }
    } else {
      if (event.target.querySelector('span').innerText === '查 询') {
        if (Object.keys(params).indexOf('startDate') === -1) {
          params.startDate = ''
        }
        if (Object.keys(params).indexOf('endDate') === -1) {
          params.endDate = ''
        }
      } else if (event.target.querySelector('span').innerText === '重 置') {
        ref.current.setFieldsValue({
          startDate: moment(),
          endDate: moment()
        })
        hiddenData = null
      }
      handleSearchParams({ ...hiddenData, ...params });
      return { ...hiddenData, ...params }
    }
  }, []);

  //导出方法
  const handleExport = () => {
    if (!exportFlag) {
      message.warning('表格数据为空');
    } else {
      const hide = message.loading('正在导出');
      let res = downloadluggagedetailExcel(searchParams)
        .then(res => {
          let blob = new Blob([res], {
            type:
              'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          });
          let elink = document.createElement('a');
          let time = moment(Date.now()).format('YYYY-MM-DD HH_ss_mm')
          elink.download = '异常行李补偿明细表' + time + '.xls'
          elink.style.display = 'none';
          elink.href = URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          document.body.removeChild(elink);
          hide();
          message.success('导出成功');
        })
        .catch(err => {
          console.log(err);
        });
    }
  };

  // 切换清空搜索
  useEffect(() => {
    hiddenData = null
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  useEffect(() => {
    if (isCollapse) {
      controlH(document.body.clientHeight - 455);
    } else {
      controlH(document.body.clientHeight - 550);
    }
  }, [isCollapse])

  const columns = [
    {
      title: '航班日期',
      dataIndex: 'flightDate',
      width: 120,
      hideInSearch: true
    },
    {
      title: '航班号',
      dataIndex: 'flightNumber',
      width: 100,
      hideInSearch: true
    },
    {
      title: '航班开始日期',
      dataIndex: 'startDate',
      order: 7,
      renderFormItem: (_, { onChange, value, ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            onChange={onChange}
            format={format}
            value={value}
            {...rest}
          />
        );
      },
      hideInTable: true
    },
    {
      title: '航班结束日期',
      dataIndex: 'endDate',
      order: 6,
      renderFormItem: (_, { onChange, value, ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            onChange={onChange}
            format={format}
            value={value}
            {...rest}
          />
        );
      },
      hideInTable: true,
    },
    {
      // 多个查询选项
      title: '起飞航站',
      dataIndex: 'org',
      width: 100,
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder="请选择"
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {selectData &&
              selectData.map((v, i) => {
                return (
                  <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      },
    },
    {
      // 多个查询选项
      title: '到达航站',
      dataIndex: 'dst',
      width: 100,
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder="请选择"
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {selectData &&
              selectData.map((v, i) => {
                return (
                  <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      },
    },
    {
      // 多个查询选项
      title: '处理航站',
      dataIndex: 'terminalCode',
      width: 100,
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder="请选择"
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {selectData &&
              selectData.map((v, i) => {
                return (
                  <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      },
    },
    {
      title: '补偿类型',
      dataIndex: 'accidentType',
      width: 100,
      renderFormItem: (_, { onChange, value }) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder='请选择'
            filterOption={true}
            optionFilterProp="children"
            onChange={onChange}
            value={value ? value : undefined}
          >
            {
              _accidentType && _accidentType.length && _accidentType.map((v, i) => {
                return (
                  <Option key={v.id}>{v.name}</Option>
                )
              })
            }
          </Select>
        );
      }
    },
    {
      title: '地区类型',
      dataIndex: 'dOrI',
      width: 120,
      renderFormItem: (_, { onChange, value }) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder='请选择'
            filterOption={true}
            optionFilterProp="children"
            onChange={onChange}
            value={value ? value : undefined}
          >
            {
              _dOrI && _dOrI.length && _dOrI.map((v, i) => {
                return (
                  <Option key={v.id}>{v.name}</Option>
                )
              })
            }
          </Select>
        );
      }
    },
    {
      title: '旅客姓名',
      dataIndex: 'passengerName',
      width: 120
    },
    {
      title: '票号',
      dataIndex: 'ticketNumber',
      width: 140,
      hideInSearch: true
    },
    {
      title: '补偿单号',
      dataIndex: 'orderId',
      width: 100,
      hideInSearch: true,
      ellipsis: true
    },
    {
      title: '事故单号',
      dataIndex: 'accidentId',
      width: 100,
      hideInSearch: true,
      ellipsis: true
    },
    {
      title: '行李编号',
      dataIndex: 'pkgNumber',
      width: 120,
      hideInSearch: true
    },
    {
      title: '机号',
      dataIndex: 'planeCode',
      width: 100,
      hideInSearch: true
    },
    {
      title: '机型',
      dataIndex: 'flightModel',
      width: 90,
      hideInSearch: true
    },
    {
      title: '机型',
      dataIndex: 'planeType',
      key: 'planeType',
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            mode="multiple"
            allowClear={true}
            placeholder="请选择"
          >
            <Option key='A319'>A319</Option>
            <Option key='A320'>A320</Option>
            <Option key='A321'>A321</Option>
            <Option key='A330'>A330</Option>
            <Option key='A350'>A350</Option>
          </Select>
        );
      },
      hideInTable: true
    },
    {
      title: '重量',
      dataIndex: 'littlePkgWeight',
      width: 100,
      hideInSearch: true
    },
    {
      title: '补偿金额',
      dataIndex: 'compensateAmount',
      width: 100,
      hideInSearch: true
    },
    {
      title: '领取渠道',
      dataIndex: 'applyWay',
      width: 100,
      hideInSearch: true
    }
  ];

  return (
    <>
      <ProTable
        actionRef={actionRef}
        formRef={ref}
        rowKey="id"
        className={styles.compensationlist}
        headerTitle={
          <div>
            <span style={{ paddingRight: 10, fontWeight: "bold", color: "#000" }}>补偿明细表</span>
          </div>
        }
        options={{ density: false, fullScreen: true, reload: false, setting: true }}
        beforeSearchSubmit={beforeSearchSubmit}
        search={{
          span: 6,
          onCollapse: val => {
            controlC(val)
            if (!val && hiddenData) {
              ref.current.setFieldsValue({
                org: hiddenData.org,
                dst: hiddenData.dst,
                terminalCode: hiddenData.terminalCode,
                accidentType: hiddenData.accidentType,
                dOrI: hiddenData.dOrI,
                passengerName: hiddenData.passengerName,
                ticketNumber: hiddenData.ticketNumber,
                planeType: hiddenData.planeType,
              })
            } else {
              hiddenData = ref.current.getFieldsValue()
            }
          }
        }}
        toolBarRender={() => [
          <AuthComponent authCode="banksearchSystem.compensationlist.export">
            <Button icon="download" type="primary" onClick={() => handleExport()} size="small">
              导出
            </Button>
          </AuthComponent>
        ]}
        postData={data => {
          if (data.length === 0) {
            handleExportFlag(false)
          } else {
            handleExportFlag(true)
          }
          return data
        }}
        request={params => {
          if (!params['startDate'] && !params['endState'] && firstLoadDate) {
            setFirstLoadDate(false)
            params['startDate'] = moment().format('YYYY-MM-DD')
            params['endDate'] = moment().format('YYYY-MM-DD')
            ref.current.setFieldsValue({
              startDate: moment(),
              endDate: moment()
            })
          }
          return irregularluggagedetailTable(params);
        }}
        columns={columns}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第${range[0]}-${range[1]}条 共 ${total} 项`,
          defaultPageSize: 20,
          pageSizeOptions: ['20', '30', '40']
        }}
        scroll={{ x: 1100, y: height }}
      />
    </>
  );
};

export default Form.create()(Compensationlist);
